<?php if (!defined('BASEPATH'))exit('No direct script access allowed');

class Site extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('new_task_model');
        $this->load->model('users_spread_model');
        $this->load->model('finance_list_model');
        $this->load->model('experience_list_model');
        $this->load->model('bbs_dialog_model');
    }

    function login() {
        $mess = array();
        if($_POST){
            $rectUrl = isset($_POST['rectUrl']) ? trim($_POST['rectUrl']) : "" ;//跳转链接
            $rectUrl = strpos($rectUrl,"tan66") ? ((strpos($rectUrl,"register") || strpos($rectUrl,"findpwd")) ? web_url("") : $rectUrl)  : web_url("");
            
            if($this->bbs_userinfo){
                $mess['reqStatus'] = true;
                $mess['errorMsg'] = '登录成功';
                $mess['redirectURL'] = $rectUrl;
                echo JSON($mess);exit;
            }
            $loginName = isset($_POST['loginName']) ? trim($_POST['loginName']) : "" ;//登录用户名
            $loginPass = isset($_POST['loginPass']) ? trim($_POST['loginPass']) : "" ;//登录密码
            $checkCode = isset($_POST['checkCode']) ? trim($_POST['checkCode']) : "" ;//验证登录码
            
            //检测用户名
            if(!$loginName){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '登录用户名不能为空';
                echo JSON($mess);exit;
            }
            
            if(!$loginPass){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '登录密码不能为空';
                echo JSON($mess);exit;
            }
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '请解锁滑块验证码';
                echo JSON($mess);exit;
            }
            
            $uinfo = "";
            if(check_email($loginName)){
                $uinfo = $this->users_model->get_user(array('email'=>$loginName,"is_line"=>0));
            }elseif(check_mobile($loginName)){
                $uinfo = $this->users_model->get_user(array('mobile'=>$loginName,"is_line"=>0));
            }else{
                $uinfo = $this->users_model->get_user(array('username'=>$loginName,"is_line"=>0));
            }
            if(!$uinfo){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '登录用户名输入有误';
                echo JSON($mess);exit;
            }
            
            //查看是否被锁定
            if($uinfo['status'] == 0){
                $mess['errorMsg'] = '对不起，您的账户处于锁定状态，禁止登录';
                $mess['errorCode'] = 1008;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            $ip = $this->input->ip_address();
            $is_pass = $uinfo['password'] == md5(md5($loginPass) . $uinfo['salt']);
            
            /**同盾接口防护start*/
//            $fraud_config = $this->web_config['FRAUD'];
//            $params = array(
//                'event_id' => $fraud_config['login'],
//                'token_id' => $this->session_id,
//                'account_login' => $loginName,
//                'ip_address' => $ip,
//                'state' => !$is_pass ? 1 : 0,
//            );
//            $response = $this->fraud->init($params)->invoke_fraud_api();
//            if(!$response['success']){
//                $mess['errorMsg'] = $response['reason_code'];
//                $mess['errorCode'] = 1000;
//                $mess['reqStatus'] = false;
//                echo JSON($mess);exit;
//            }
            /**同盾接口防护end*/
            
            //验证密码
            if(!$is_pass){
                $mess['errorMsg'] = '登录密码错误';
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            if($checkCode != $this->session->userdata('login_code')){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '请解锁滑块验证码';
                echo JSON($mess);exit;
            }
            
            //登录成功，写入日志记录
            $log_data = array();
            $log_data['user_id'] = $uinfo['user_id'];
            $log_data['events'] = 'login';
            $log_data['content'] = '登录成功';
            $log_data['ip'] = $this->input->ip_address();
            $log_data['create_time'] = time();
            
            $this->users_model->insert_log($log_data);
            //更改用户信息
            $data = array();
            $data['login_times'] = $uinfo['login_times'] + 1;
            $data['last_ip'] = $uinfo['login_ip'];
            $data['last_time'] = $uinfo['login_time'];
            $data['login_ip'] = $this->input->ip_address();
            $data['login_time'] = time();
            $this->users_model->user_update($data,$uinfo['user_id']);
            //登录
            $info = array();
            $info['user_id'] = $uinfo['user_id'];
            $info['username'] = $uinfo['username'];
            $info['mobile'] = $uinfo['mobile'];
            $info['email'] = $uinfo['email'];
            $info['last_ip'] = $data['last_ip'];
            $info['last_time'] = $data['last_time'];
            $this->session->set_userdata('userinfo', $info);
            
            //跨域登录
            setcookie('tan_uuid',  encrypt_user_id($uinfo['user_id']),time()+3600*24*2, "/", ".tan.com");
            
            $mess['errorMsg'] = '登录成功';
            $mess['reqStatus'] = true;
            $mess['redirectURL'] = $rectUrl;
            echo JSON($mess);exit;
        }
        
        if(isset($_GET['redirectUrl'])){
            $this->session->set_userdata('userinfo', "");
            $this->bbs_userinfo = null;
        }
        
        if($this->bbs_userinfo){
            web_redirect("account.html");
        }
        $check_code = md5(time()."TaN66");
        $this->session->set_userdata("login_code", $check_code);
        $this->assign("check_code",$check_code);
        $this->assign("rect_url",  isset($_GET['redirectUrl']) ? urldecode($_GET['redirectUrl']) :$_SERVER['HTTP_REFERER']);
        $this->assign("title", "登录");
        $this->display("site/login.html");
    }
    
    
    function register() {
        
        //获取新手任务配置
        $this->new_task = $this->config_task['new_task'];
        $mess = array();
        if($_POST){
            $rectUrl = isset($_POST['rectUrl']) ? trim($_POST['rectUrl']) : "" ;//跳转链接
            $rectUrl = strpos($rectUrl,"tan66") ? ((strpos($rectUrl,"register") || strpos($rectUrl,"findpwd") || strpos($rectUrl,"login")) ? web_url("") : $rectUrl)  : web_url("");
            
            if($this->bbs_userinfo){
                $mess['reqStatus'] = true;
                $mess['redirectURL'] = $rectUrl;
                echo JSON($mess);exit;
            }
            
            $username = isset($_POST['regName']) ? trim($_POST['regName']) : "";//注册用户名
            $password = isset($_POST['regPass']) ? trim($_POST['regPass']) : "";//密码
            $checkCode = isset($_POST['checkCode']) ? trim($_POST['checkCode']) : "" ;//验证注册验证码
            $ip = $this->input->ip_address();
            /**同盾接口防护start*/
//            $fraud_config = $this->web_config['FRAUD'];
//            $params = array(
//                'event_id' => $fraud_config['reg'],
//                'token_id' => $this->session_id,
//                'account_login' => $username,
//                'account_mobile' => '',
//                'ip_address' => $ip,
//            );
//            $response = $this->fraud->init($params)->invoke_fraud_api();
//            if(!$response['success']){
//                $mess['errorMsg'] = $response['reason_code'];
//                $mess['errorCode'] = 1000;
//                $mess['reqStatus'] = false;
//                echo JSON($mess);exit;
//            }
            /**同盾接口防护end*/
            
            //验证码用户名是否为空
            if(!$username){
                $mess['errorMsg'] = "用户名不能为空";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            //验证用户名格式
            if(!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/",$username) && !preg_match("/^[a-zA-Z]{6,16}$/",$username)){
                $mess['errorMsg'] = '用户名格式不正确';
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证码用户名的唯一性
            if($this->users_model->get_user_flag(array("username"=>$username,"is_line"=>0))){
                $mess['errorMsg'] = '用户名已经被注册';
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证密码
            if(!$password){
                $mess['errorMsg'] = '密码不能为空';
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '请解锁滑块验证码';
                echo JSON($mess);exit;
            }
            
            if($checkCode != $this->session->userdata('register_code')){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = '请解锁滑块验证码';
                echo JSON($mess);exit;
            }
            
            $parent_id = $this->session->userdata('parent_id') ? $this->session->userdata('parent_id') : 0;
            //判断是否有效用户
            if($parent_id && $parent_id != "" && $parent_id != 0){
                $parent_user = $this->users_model->get_user_by_uid($parent_id);
                if($parent_user && $parent_user['status'] == 0){
                    $mess['errorMsg'] = '注册失败';
                    $mess['errorCode'] = 1000;
                    $mess['reqStatus'] = false;
                    echo JSON($mess);exit;
                }
            }
            
             //生成salt
            $salt = random_string('alnum', 6);
            //生成加密密码
            $md5pass = md5(md5($password) . $salt);
            //写入数据库
            $data = array();
            $data['username'] = $username;
            $data['password'] = $md5pass;
            $data['parent_id'] = $parent_id;
            $data['mobile'] = '';
            $data['email'] = '';
            $data['salt'] = $salt;
            $data['reg_ip'] = $this->input->ip_address();
            $data['reg_time'] = time();
            $data['login_times'] = 1;
            $data['login_ip'] = $this->input->ip_address();
            $data['login_time'] = time();
            $data['last_ip'] = $this->input->ip_address();
            $data['last_time'] = time();
            
            //创建用户注册信息
            $user_id = $this->users_model->insert($data);
            $month = date('Ym');
            $day = date('Ymd');
            
            
            
            if($user_id){
                
                $task_first_finance = $this->new_task[0]['award_finance'];//首次任务注册奖励
                $task_first_experience = $this->new_task[0]['award_experience'];//首次任务注册奖励
                //推荐人信息
                if($parent_id){
                    $spread_data = array('user_id'=>$user_id,'parent_id'=>$parent_id,'create_time'=>  time(),'month'=>$month,'day'=>$day);
                    $this->users_spread_model->insert($spread_data);
                    //插入推广记录
                }
                //用户附加信息
                $img_index = rand(0, 9);
                $info_data = array();
                $info_data['user_id'] = $user_id;
                $info_data['head_img'] = "http://static.tan66.com/upfiles/head/s/".  $img_index.".jpg";
                $info_data['head_small_img'] = "http://static.tan66.com/upfiles/head/m/".  $img_index.".jpg";
                $info_data['nickname'] = "tan66-".encrypt_user_id($user_id);
                $info_data['create_time'] = time();
                $this->users_model->insert_user_info($info_data);//插入用户附加信息
                //用户账户信息
                $account_data = array();
                $account_data['user_id'] = $user_id;
                $account_data['total'] = $task_first_finance;//账户总额
                $account_data['balance'] = $task_first_finance;//可用余额
//                $account_data['experience'] = $task_first_experience;//当前积分
//                $account_data['experience_balance'] = $task_first_experience;//可用积分
                $this->account_model->insert($account_data);//插入用户账号信息
                //新手任务
                $new_user_task1 = array();
                $new_user_task1['user_id'] = $user_id;
                $new_user_task1['step'] = 1;
                $new_user_task1['reward_worth'] = $this->new_task[0]['award_finance'];
                $new_user_task1['reward_experience'] = $this->new_task[0]['award_experience'];
                $new_user_task1['is_finish'] = 1;
                $new_user_task1['is_receive'] = 1;
                $new_user_task1['receive_time'] = time();
                $new_user_task1['finish_time'] = time();
                $new_user_task1['create_time'] = time();
                $this->new_task_model->insert($new_user_task1);//新手任务第一步
                
                $new_user_task2 = array();
                $new_user_task2['user_id'] = $user_id;
                $new_user_task2['step'] = 2;
                $new_user_task2['reward_worth'] = $this->new_task[1]['award_finance'];
                $new_user_task2['reward_experience'] = $this->new_task[1]['award_experience'];
                $new_user_task2['is_finish'] = 0;
                $new_user_task2['is_receive'] = 0;
                $new_user_task2['receive_time'] = 0;
                $new_user_task2['finish_time'] = 0;
                $new_user_task2['create_time'] = time();
                $this->new_task_model->insert($new_user_task2);//新手任务第二步
                
                $new_user_task3 = array();
                $new_user_task3['user_id'] = $user_id;
                $new_user_task3['step'] = 3;
                $new_user_task3['reward_worth'] = $this->new_task[2]['award_finance'];
                $new_user_task3['reward_experience'] = $this->new_task[2]['award_experience'];
                $new_user_task3['is_finish'] = 0;
                $new_user_task3['is_receive'] = 0;
                $new_user_task3['receive_time'] = 0;
                $new_user_task3['finish_time'] = 0;
                $new_user_task3['create_time'] = time();
                $this->new_task_model->insert($new_user_task3);//新手任务第三步
                
                //奖励通知
                $message = "恭喜您完成新手任务第一步【".$this->new_task[0]['title']."】,奖励您".$this->new_task[0]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[0]['award_experience']."积分
                $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time())); 
                
                $current_time = time();
                
                //资金明细
                $finance_data = array();
                $finance_data['user_id'] = $user_id;
                $finance_data['content'] = '新人注册奖励礼包'.$task_first_finance.'溜溜币';
                $finance_data['finance'] = $task_first_finance;
                $finance_data['finance_balance'] = $account_data['balance'];
                $finance_data['reward_type'] = 'task_award';
                $finance_data['type'] = 1;
                $finance_data['create_time'] = $current_time;
                $finance_data['month'] = $month;
                $finance_data['day'] = $day;
                $this->finance_list_model->insert($finance_data);
                        
                //积分明细
//                $experience_data = array();
//                $experience_data['user_id'] = $user_id;
//                $experience_data['content'] = '新人注册奖励礼包'.$task_first_experience.'积分';
//                $experience_data['experience'] = $task_first_experience;
//                $experience_data['experience_balance'] = $account_data['experience_balance'];
//                $experience_data['reward_type'] = 'task_award';
//                $experience_data['type'] = 1;
//                $experience_data['create_time'] = $current_time;
//                $experience_data['month'] = $month;
//                $experience_data['day'] = $day;
//                $this->experience_list_model->insert($experience_data);
                
                /*********社区相关start********/
                //创建社区用户表
                $this->bbs_user_model->insert_bbs_user(array("user_id"=>$user_id,"salt"=>$salt,"reg_time"=>  time(),"group_id"=>1,"create_time"=>  time()));
                //创建社区用户账户表
                $this->bbs_user_model->insert_bbs_account(array("user_id"=>$user_id));
                //创建社区个人统计表
                $this->bbs_user_model->insert_bbs_count(array("user_id"=>$user_id));
                
                //添加个人动态
                //$this->insert_behavior(array('user_id'=>$this->userinfo['user_id'],"operator_id"=>0,"event_type"=>"event_reg"));
                //系统通知
                $this->insert_notice(array('user_id'=>0,"operator_id"=>0,"recieve_id"=>$user_id,"event_type"=>"event_reg","type"=>"system","content"=>"欢迎来到弹溜溜社区大家庭！！"));
                /*********社区相关end********/
                
                //发送欢迎私信
                $this->send_dialog($user_id,$salt);
                
                //用户日志
                $log_data = array();
                $log_data['user_id'] = $user_id;
                $log_data['events'] = 'register';
                $log_data['content'] = '注册成功';
                $log_data['ip'] = $this->input->ip_address();;
                $log_data['create_time'] = time();
                $this->users_model->insert_log($log_data);
                
                //自动登录
                $info = array();
                $info['user_id'] = $user_id;
                $info['username'] = $data['username'];
                $info['mobile'] = $data['mobile'];
                $info['email'] = $data['email'];
                $info['last_ip'] = $data['last_ip'];
                $info['last_time'] = $data['last_time'];
                $this->session->set_userdata('userinfo', $info);
                
                //跨域登录
                setcookie('tan_uuid',  encrypt_user_id($user_id),time()+3600*24*2, "/", ".tan.com");
                
                $mess['errorMsg'] = '注册成功';
                $mess['reqStatus'] = true;
                $mess['redirectURL'] = $rectUrl;
                echo JSON($mess);exit;
                
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "对不起，注册失败";
                echo JSON($mess);exit;
            }
            
            
        }
        
        if(isset($_GET['redirectUrl'])){
            $this->session->set_userdata('userinfo', "");
        }
        
        if($this->bbs_userinfo){
            web_redirect("account.html");
        }
        $check_code = md5(time()."TaN66");
        $this->session->set_userdata("register_code", $check_code);
        $this->assign("check_code",$check_code);
        $this->assign("rect_url",  isset($_GET['redirectUrl']) ? urldecode($_GET['redirectUrl']) :$_SERVER['HTTP_REFERER']);
        $this->assign("title", "注册");
        $this->display("site/register.html");
    }
    function findpwd() {
        
        if($this->bbs_userinfo){
            web_redirect("account.html");
        }
        
        if($_POST){
            $uMobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";
            $smsCode = isset($_POST['smsCode']) ? trim($_POST['smsCode']) : "";
            if(!$uMobile){
                $mess['errorMsg'] = "手机验证失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            $flag = $this->users_model->get_user_flag(array('mobile'=>$uMobile,"is_line"=>0));
            if(!$flag){
                $mess['errorMsg'] = "手机验证失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            if(!$smsCode){
                $mess['errorMsg'] = "验证码不能为空";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            if($smsCode != $this->session->userdata('sms_code')){
                $mess['errorMsg'] = "验证码验证失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            $this->session->set_userdata("sms_code","");
            $this->session->set_userdata("find_flag",true);
            $this->session->set_userdata("umobile",$uMobile);
            $mess['errorMsg'] = '';
            $mess['reqStatus'] = true;
            $mess['redirectURL'] = web_url("account/findpwd_next");
            echo JSON($mess);exit;
        }
        $this->session->set_userdata("find_flag",null);
        $this->assign("step", 1);
        $this->display("site/findpwd.html");
    }
    //找回密码-第二步
    function findpwd_next(){
        if($this->bbs_userinfo){
            web_redirect("account.html");
        }
        if($_POST){
            $umobile = $this->session->userdata('umobile');
            $newPass = isset($_POST['newPass']) ? trim($_POST['newPass']) : "";
            if(!$newPass){
                $mess['errorMsg'] = "新密码验证失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            $uinfo = $this->users_model->get_user(array("mobile"=>$umobile,"is_line"=>0));
            if(!$uinfo){
                $mess['errorMsg'] = "身份校验失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            $newLoginPass = md5(md5($newPass) . $uinfo['salt']);
            $data = array("password"=>$newLoginPass);
            $result = $this->users_model->user_update($data,  $uinfo['user_id']);
            if($result){
                
                $mess['reqStatus'] = true;
                $mess['redirectURL'] = web_url("account/findpwd_over");
                echo JSON($mess);exit;
            }else{
                $mess['errorMsg'] = "操作失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
        }
        if(!$this->session->userdata('find_flag')){
            redirect("site/findpwd");
        }
        $this->assign("step", 2);
        $this->display("site/findpwd.html");
    }
    
    //找回密码-第三步
    function findpwd_over(){
        if($this->bbs_userinfo){
            web_redirect("account.html");
        }
        if(!$this->session->userdata('find_flag')){
            redirect("account/findpwd");
        }
        
        $this->session->set_userdata('find_flag',"");
        
        $this->assign("step", 3);
        $this->display("site/findpwd.html");
    }
    
    /**
     * 登录用户名检测是否存在
     */
    function checkUserLogin() {
        if(isset($_POST['loginName'])){
            $loginName = isset($_REQUEST['loginName']) ? trim($_REQUEST['loginName']) : "";
            $name_flag = false;
            if($loginName){
                if(check_email($loginName)){
                    $name_flag = $this->users_model->get_user_flag(array('email'=>$loginName,"is_line"=>0));
                }elseif(check_mobile($loginName)){
                    $name_flag = $this->users_model->get_user_flag(array("mobile"=>$loginName,"is_line"=>0));
                }else{
                    $name_flag = $this->users_model->get_user_flag(array("username"=>$loginName,"is_line"=>0));
                }
            }
            if($name_flag){
                echo JSON(true);
            }else{
                echo JSON(false);
            }
        }else{
            echo JSON(false);
        }
    }
    
    //注册验证用户是否存在,检测用户唯一性
    public function checkusersign(){
        if(isset($_POST['regName'])){
            if($this->users_model->get_user_flag(array('username'=>$_POST['regName'],"is_line"=>0))){
                echo JSON(false);
            }else{
                echo JSON(true);
            }
        }
    }
    /**
     * 绑定手机验证
     */
    function checkLoginMobile(){
        if(isset($_POST['uMobile']) && trim($_POST['uMobile'] != "")){
            $mobile = trim($_POST['uMobile']);
            $flag = $this->users_model->get_user_flag(array('mobile'=>$mobile,"is_line"=>0));
            if($flag){
                echo JSON(true);
            }else{
                echo JSON(false);
            }
        }else{
            echo JSON(false);
        }
    }
    function checkSmsCode(){
        if (isset($_POST['smsCode']) && trim($_POST['smsCode'])) {
            if ($this->session->userdata('sms_code') != trim($_POST['smsCode'])) {
                echo JSON(false);
            } else {
                echo JSON(true);
            }
        }else{
            echo JSON(false);
        }
    }
    
    //发送短信
    function sendSMSCode(){
        if($_POST){
            $type = isset($_POST['type']) ? trim($_POST['type']) : "";
            $value = isset($_POST['value']) ? trim($_POST['value']) : "";
            if(!$type){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "传递参数有误";
                echo JSON($mess);exit;
            }
            $flag = false;
            if($type == "m"){
                $flag = preg_match("/^1[3|4|5|7|8]\d{9}$/", $value);
                if(!$flag){
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = "手机格式不正确";
                    echo JSON($mess);exit;
                }
                
                $postData = array();
                $postData['mobile'] = $value;
                $postData['tpl'] = 'mmp';//找回密码模板
                $postData['from_type'] = 1;
                $result = $this->crypt->POST_Api($this->remote_url['sms_url'],$postData);
                $result = json_decode($result,true);
                if($result['result'] == 1){
                    $this->session->set_userdata("sms_code",$result['code']);
                    $this->session->set_userdata("code_vilid_time",$result['time']);
                    $this->session->set_userdata("check_mobile",$value);
                    $mess['errorMsg'] = '发送成功';
                    $mess['time'] = 60;
                    $mess['reqStatus'] = true;
                    echo JSON($mess);exit;
                }else{
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = $result['errmsg'];
                    echo JSON($mess);exit;
                }
            }else{
                $flag = preg_match("/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/", $value);
                if(!$flag){
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = "邮箱格式不正确";
                    echo JSON($mess);exit;
                }
                //验证码
                $vcode = rand(100000, 999999);
                $message = "尊敬的用户:您正在进行邮箱验证，验证码：".$vcode."。如非本人操作，请忽略。";
                //发送邮箱接口
                $result = $this->email->send($value,'邮箱验证',$message);
                if($result['result'] == 0){
                    $this->session->set_userdata("email_code",$vcode);
                    $mess['errorMsg'] = '发送成功';
                    $mess['time'] = 60;
                    $mess['reqStatus'] = true;
                    echo JSON($mess);exit;
                }else{
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = $result['info'];
                    echo JSON($mess);exit;
                }
            }
            
        }else{
            $mess['reqStatus'] = false;
            $mess['errorCode'] = 1005;
            $mess['errorMsg'] = "非法请求";
            echo JSON($mess);
        }
    }
    /**
     * 发送绑定手机验证码
     */
    function send_bmobile_code(){
        if($_POST){
            $mobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";
            $flag = preg_match("/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-3,5-9]{1})|(17[0,1,3,5-8]{1})|(18[0-9]{1}))+\d{8})$/", $mobile);
            if(!$flag){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "手机格式不正确";
                echo JSON($mess);exit;
            }
                    
            $postData = array();
            $postData['mobile'] = $mobile;
            $postData['tpl'] = 'mmp';//找回密码模板
            $postData['from_type'] = 2;
            $result = $this->crypt->POST_Api($this->remote_url['sms_url'],$postData);
            $result = json_decode($result,true);
            if($result['result'] == 1){
                $this->session->set_userdata("thirdlogin_code",$result['code']);//
                $this->session->set_userdata("thirdlogin_mobile",$mobile);
                $mess['reqStatus'] = true;
                echo JSON($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "操作过于频繁";
                echo JSON($mess);exit;
            }
        }
    }
    //内容反馈
    function feedback(){
        $mess = array();
        $feed_type = trim($_POST['feed_type']);
        $feed_page = trim($_POST['feed_page']);
        $feed_content = trim($_POST['feed_content']);
        $feed_contact = trim($_POST['feed_contack']);
        
        $data = array();
        $data['feed_type'] = $feed_type;
        $data['feed_page'] = $feed_page;
        $data['feed_content'] = $feed_content;
        $data['feed_contact'] = $feed_contact;
        $data['is_deal'] = 0;
        $data['create_time'] = time();
        $this->db->insert("feedback",$data);
        if($this->db->affected_rows()){
            $mess['reqStatus'] = true;
            $mess['errorMsg'] = "提交成功，谢谢您的宝贵意见或建议";
        }else{
            $mess['reqStatus'] = false;
            $mess['errorMsg'] = "操作失败，请稍后重试";
        }
        echo JSON($mess);die;
    }
    function logout(){
        setcookie("tan_uuid", "", time()-1,"/", ".tan.com");
        $this->session->sess_destroy();
        if (strpos('host' . $_SERVER['HTTP_HOST'], "www") == false) {
            $loginout2 = '<script type="text/javascript" src="' . site_url('account/logout') .
                    '" reload="1"></script>';
        } else {
            $loginout2 = '<script type="text/javascript" src="' . site_url('account/logout') .
                    '" reload="1"></script>';
        }
        echo $loginout2 .
        '<script type="text/javascript">window.location.href="' . $this->redirectLink .
        '"</script>';
    }
    
    function alogin(){
        $uname = trim($_GET['uname']);
        $uinfo = $this->users_model->get_user_by_username($uname);
        if(!$uinfo){
            echo "用户不存在";die;
        }
        //登录
        $info = array();
        $info['user_id'] = $uinfo['user_id'];
        $info['username'] = $uinfo['username'];
        $info['mobile'] = $uinfo['mobile'];
        $info['email'] = $uinfo['email'];
        $info['last_ip'] = $uinfo['last_ip'];
        $info['last_time'] = $uinfo['last_time'];
        $this->session->set_userdata('userinfo', $info);
        //跨域登录
        setcookie('tan_uuid',  encrypt_user_id($uinfo['user_id']),time()+3600*24*2, "/", ".tan.com");
        web_redirect("account.html");
    }
    //第三方qq登录
    function qq_login(){
        $this->load->library('Oauth');//qq第三方登录
        $qc = new QC();
        $qc->qq_login();
    }
    //第三方weibo登录
    function weibo_login(){
        $this->load->library('Weibo');//新浪微博第三方登录
        session_start();
        $wc = new SaeTOAuthV2(WB_AKEY,WB_SKEY);
        $redirect_url = $wc->getAuthorizeURL(WB_CALLBACK_URL);
        header("Location:".$redirect_url);
    }
    //第三方微信登录
    function weixin_login(){
        $this->load->library('Weixin');//微信第三方登录
        $wx = new Weixin();
        $config = array(
            "redirectUri" => "http://www.tan66.com/callback/weixin_login.html",
            "state" => 1
        );
        $wx->get_code($config);
    }
    /**
     * 第三方绑定注册
     */
    function third_bind(){
        if($_POST){
            $umobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";//绑定手机号
            $upass = isset($_POST['upass']) ? trim($_POST['upass']) : "tll123456";//初始化注册密码
            $checkCode = isset($_POST['uCode']) ? trim($_POST['uCode']) : "" ;//验证注册验证码
            $qc_info = isset($_POST['uQcinfo']) ? json_decode(base64_decode(trim($_POST['uQcinfo'])),true) : "" ;//第三方账户信息
            $utype = isset($_POST['uType']) ? trim($_POST['uType']) : "" ;//第三方类型
            //验证手机号是否为空
            if(!$umobile){
                $mess['errorMsg'] = "手机号不能为空";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证手机号格式
            if(!preg_match("/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-3,5-9]{1})|(17[0,1,3,5-8]{1})|(18[0-9]{1}))+\d{8})$/",$umobile)){
                $mess['errorMsg'] = '手机号格式不正确';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机验证码不能为空';
                echo JSON($mess);exit;
            }
            if($checkCode != $this->session->userdata('thirdlogin_code')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '验证码输入有误或已失效';
                echo JSON($mess);exit;
            }
            if($umobile != $this->session->userdata('thirdlogin_mobile')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机和验证码不匹配';
                echo JSON($mess);exit;
            }
            $this->session->set_userdata("thirdlogin_code","");
            $this->session->set_userdata("thirdlogin_mobile","");
            
            //验证码用户名
            $uinfo = $this->users_model->get_user(array('mobile'=>$umobile,"is_line"=>0));
            $user_id = $uinfo["user_id"];
            if($uinfo){//老用户绑定
                if($utype == "qq"){//qq
                    $this->users_model->del_qq_bind($uinfo['user_id']);
                    $bind_data['user_id'] = $uinfo['user_id'];
                    $bind_data['access_token'] = $qc_info['access_token'];
                    $bind_data['open_id'] = $qc_info['open_id'];
                    $bind_data['nickname'] = $qc_info['nickname'];
                    $bind_data['sex'] = $qc_info['gender'];
                    $bind_data['province'] = $qc_info['province'];
                    $bind_data['city'] = $qc_info['city'];
                    $bind_data['head_img_s'] = $qc_info['head_img_s'];
                    $bind_data['head_img_b'] = $qc_info['head_img_b'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_qq_bind($bind_data);
                }elseif($utype == "sina"){//新浪
                    $this->users_model->del_weibo_bind($uinfo['user_id']);
                    $bind_data['user_id'] = $uinfo['user_id'];
                    $bind_data['access_token'] = $qc_info['access_token'];
                    $bind_data['uid'] = $qc_info['open_id'];
                    $bind_data['nickname'] = $qc_info['nickname'];
                    $bind_data['sex'] = $qc_info['gender'];
                    $bind_data['province'] = $qc_info['province'];
                    $bind_data['city'] = $qc_info['city'];
                    $bind_data['head_img_s'] = $qc_info['head_img_s'];
                    $bind_data['head_img_b'] = $qc_info['head_img_b'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_weibo_bind($bind_data);
                }elseif($utype == "weixin"){//微信
                    $this->users_model->del_weixin_bind($uinfo['user_id']);
                    $bind_data = array();
                    $bind_data['user_id'] = $uinfo['user_id'];
                    $bind_data['unionid'] = $qc_info['unionid'];
                    $bind_data['open_id'] = $qc_info['open_id'];
                    $bind_data['nickname'] = $qc_info['nickname'];
                    $bind_data['sex'] = $qc_info['sex'];
                    $bind_data['province'] = $qc_info['province'];
                    $bind_data['city'] = $qc_info['city'];
                    $bind_data['headimgurl'] = $qc_info['headimgurl'];
                    $bind_data['privilege'] = $qc_info['privilege'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_weixin_bind($bind_data);
                }
            }else{//新用户注册
                //获取新手任务配置
                $this->new_task = $this->config_task['new_task'];
                //验证密码
                if(!$upass){
                    $mess['errorMsg'] = '密码不能为空';
                    $mess['reqStatus'] = false;
                    echo JSON($mess);exit;
                }
                /*******************/
                //判断是否线下注册,如果是，则删除
                $line_user = $this->users_model->get_user(array("mobile"=>$umobile,"is_line"=>1));
                if($line_user){
                    $user_id = $line_user['user_id'];
                    $this->db->where(array('mobile'=>$umobile))->update("tan_users_line",array('is_reg'=>1));
                }
                /***********************/
                //生成salt
                $salt = random_string('alnum', 6);
                //生成加密密码
                $md5pass = md5(md5($upass) . $salt);
                //写入数据库
                $data = array();
                $data['username'] = "tll".$umobile;
                $data['password'] = $md5pass;
                $data['parent_id'] = 0;
                $data['mobile'] = $umobile;
                $data['email'] = '';
                $data['salt'] = $salt;
                $data['mobile_isApprove'] = 1;
                $data['reg_ip'] = $this->input->ip_address();
                $data['reg_time'] = time();
                $data['reg_flag'] = 1;//注册来源(1、PC，2、微信，3、Android，4、ios)
                $data['login_times'] = 1;
                $data['login_ip'] = $this->input->ip_address();
                $data['login_time'] = time();
                $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
                $data['last_ip'] = $this->input->ip_address();
                $data['last_time'] = time();
                if($user_id){
                    $data['is_line'] = 0;
                    $this->db->where("user_id",$user_id)->update("tan_users",$data);
                }else{
                    //创建用户注册信息
                    $user_id = $this->users_model->insert($data);
                }
                
                $month = date('Ym');
                $day = date('Ymd');
                if($user_id){
                    
                    if($utype == "qq"){//qq
                        $bind_data['user_id'] = $user_id;
                        $bind_data['access_token'] = $qc_info['access_token'];
                        $bind_data['open_id'] = $qc_info['open_id'];
                        $bind_data['nickname'] = $qc_info['nickname'];
                        $bind_data['sex'] = $qc_info['gender'];
                        $bind_data['province'] = $qc_info['province'];
                        $bind_data['city'] = $qc_info['city'];
                        $bind_data['head_img_s'] = $qc_info['head_img_s'];
                        $bind_data['head_img_b'] = $qc_info['head_img_b'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_qq_bind($bind_data);
                    }elseif($utype == "sina"){//新浪
                        $bind_data['user_id'] = $user_id;
                        $bind_data['access_token'] = $qc_info['access_token'];
                        $bind_data['uid'] = $qc_info['open_id'];
                        $bind_data['nickname'] = $qc_info['nickname'];
                        $bind_data['sex'] = $qc_info['gender'];
                        $bind_data['province'] = $qc_info['province'];
                        $bind_data['city'] = $qc_info['city'];
                        $bind_data['head_img_s'] = $qc_info['head_img_s'];
                        $bind_data['head_img_b'] = $qc_info['head_img_b'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_weibo_bind($bind_data);
                    }elseif($utype == "weixin"){//微信
                        $bind_data = array();
                        $bind_data['user_id'] = $user_id;
                        $bind_data['unionid'] = $qc_info['unionid'];
                        $bind_data['open_id'] = $qc_info['open_id'];
                        $bind_data['nickname'] = $qc_info['nickname'];
                        $bind_data['sex'] = $qc_info['sex'];
                        $bind_data['province'] = $qc_info['province'];
                        $bind_data['city'] = $qc_info['city'];
                        $bind_data['headimgurl'] = $qc_info['headimgurl'];
                        $bind_data['privilege'] = $qc_info['privilege'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_weixin_bind($bind_data);
                    }
                    
                    $task_first_finance = $this->new_task[0]['award_finance'];//首次任务注册奖励
                    $task_first_experience = $this->new_task[0]['award_experience'];//首次任务注册奖励

                    $task_second_finance = $this->new_task[1]['award_finance'];//首次绑定手机奖励
                    $task_second_experience = $this->new_task[1]['award_experience'];//首次绑定手机奖励
                    
                    //用户附加信息
                    $img_index = rand(0, 9);
                    $info_data = array();
                    $info_data['user_id'] = $user_id;
                    $info_data['truename'] = "";
                    $info_data['idcard'] = "";
                    $info_data['head_img'] = "http://static.tan66.com/upfiles/head/s/".  $img_index.".jpg";
                    $info_data['head_small_img'] = "http://static.tan66.com/upfiles/head/m/".  $img_index.".jpg";
                    $info_data['nickname'] = "tan66-".encrypt_user_id($user_id);
                    $info_data['create_time'] = time();
                    if($line_user){//下线用户更新
                        $this->db->where("user_id",$user_id)->update("tan_users_info",$info_data);
                    }else{
                        $this->users_model->insert_user_info($info_data);//插入用户附加信息
                    }
                    
                    //用户账户信息
                    $account_data = array();
                    $account_data['user_id'] = $user_id;
                    $account_data['total'] = $task_first_finance + $task_second_finance;//账户总额
                    $account_data['balance'] = $task_first_finance + $task_second_finance;//可用余额
                    $this->account_model->insert($account_data);//插入用户账号信息

                    //新手任务
                    $new_user_task1 = array();
                    $new_user_task1['user_id'] = $user_id;
                    $new_user_task1['step'] = 1;
                    $new_user_task1['reward_worth'] = $this->new_task[0]['award_finance'];
                    $new_user_task1['reward_experience'] = $this->new_task[0]['award_experience'];
                    $new_user_task1['is_finish'] = 1;
                    $new_user_task1['is_receive'] = 1;
                    $new_user_task1['receive_time'] = time();
                    $new_user_task1['finish_time'] = time();
                    $new_user_task1['create_time'] = time();
                    $this->new_task_model->insert($new_user_task1);//新手任务第一步

                    $new_user_task2 = array();
                    $new_user_task2['user_id'] = $user_id;
                    $new_user_task2['step'] = 2;
                    $new_user_task2['reward_worth'] = $this->new_task[1]['award_finance'];
                    $new_user_task2['reward_experience'] = $this->new_task[1]['award_experience'];
                    $new_user_task2['is_finish'] = 1;
                    $new_user_task2['is_receive'] = 1;
                    $new_user_task2['receive_time'] = time();
                    $new_user_task2['finish_time'] = time();
                    $new_user_task2['create_time'] = time();
                    $this->new_task_model->insert($new_user_task2);//新手任务第二步

                    $new_user_task3 = array();
                    $new_user_task3['user_id'] = $user_id;
                    $new_user_task3['step'] = 3;
                    $new_user_task3['reward_worth'] = $this->new_task[2]['award_finance'];
                    $new_user_task3['reward_experience'] = $this->new_task[2]['award_experience'];
                    $new_user_task3['is_finish'] = 0;
                    $new_user_task3['is_receive'] = 0;
                    $new_user_task3['receive_time'] = 0;
                    $new_user_task3['finish_time'] = 0;
                    $new_user_task3['create_time'] = time();
                    $this->new_task_model->insert($new_user_task3);//新手任务第三步

                    //奖励通知
                    $message = "恭喜您完成新手任务第一步【".$this->new_task[0]['title']."】,奖励您".$this->new_task[0]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[0]['award_experience']."积分
                    $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time())); 

                    //奖励通知
                    $message = "恭喜您完成新手任务第二步【".$this->new_task[1]['title']."】,奖励您".$this->new_task[1]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[1]['award_experience']."积分
                    $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time()+10)); 
                    $current_time = time();

                    if(1){
                       //资金明细
                        $finance_data = array();
                        $finance_data['user_id'] = $user_id;
                        $finance_data['content'] = '新人注册奖励礼包'.$task_first_finance.'溜溜币';
                        $finance_data['finance'] = $task_first_finance;
                        $finance_data['finance_balance'] = $account_data['balance'] - $task_first_finance;
                        $finance_data['reward_type'] = 'task_award';
                        $finance_data['type'] = 1;
                        $finance_data['create_time'] = $current_time;
                        $finance_data['month'] = $month;
                        $finance_data['day'] = $day;
                        $this->finance_list_model->insert($finance_data); 

                        $finance_data = array();
                        $finance_data['user_id'] = $user_id;
                        $finance_data['content'] = '首次绑定手机奖励'.$task_second_finance.'溜溜币';
                        $finance_data['finance'] = $task_second_finance;
                        $finance_data['finance_balance'] = $account_data['balance'];
                        $finance_data['reward_type'] = 'task_award';
                        $finance_data['type'] = 1;
                        $finance_data['create_time'] = $current_time + 10;
                        $finance_data['month'] = $month;
                        $finance_data['day'] = $day;
                        $this->finance_list_model->insert($finance_data);
                    }

                    /*********社区相关start********/
                    //创建社区用户表
                    $this->bbs_user_model->insert_bbs_user(array("user_id"=>$user_id,"salt"=>$salt,"reg_time"=>  time(),"group_id"=>1,"create_time"=>  time()));
                    //创建社区用户账户表
                    $this->bbs_user_model->insert_bbs_account(array("user_id"=>$user_id));
                    //创建社区个人统计表
                    $this->bbs_user_model->insert_bbs_count(array("user_id"=>$user_id));

                    //添加个人动态
                    //$this->insert_behavior(array('user_id'=>$this->userinfo['user_id'],"operator_id"=>0,"event_type"=>"event_reg"));
                    //系统通知
                    $this->insert_notice(array('user_id'=>0,"operator_id"=>0,"recieve_id"=>$user_id,"event_type"=>"event_reg","type"=>"system","content"=>"欢迎来到弹溜溜社区大家庭！！"));
                    /*********社区相关end********/
                    //发送欢迎私信
                    $this->send_dialog($user_id,$salt);
                }
            }
            
            
            //用户日志
            $log_data = array();
            $log_data['user_id'] = $user_id;
            $log_data['events'] = 'register';
            $log_data['content'] = '注册成功';
            $log_data['ip'] = $this->input->ip_address();
            $log_data['create_time'] = time();
            $this->users_model->insert_log($log_data);

            //写入登录日志
            $login_log_data = array();
            $login_log_data['user_id'] = $user_id;
            $login_log_data['login_flag'] = 1;
            $login_log_data['login_ip'] = $this->input->ip_address();;
            $login_log_data['create_time'] = time();
            $login_log_data['month'] = date("Ym");
            $login_log_data['day'] = date("Ymd");
            $this->users_model->insert_login_log($login_log_data);
            
            //跨域登录
            setcookie('tan_uuid',  encrypt_user_id($user_id),time()+3600*24*2, "/", ".tan.com");
            
            //登录
            $info = array();
            $info['user_id'] = $user_id;
            $info['username'] = $uinfo ? $uinfo['username'] : $data['username'];
            $info['mobile'] = $uinfo ? $uinfo['mobile'] : $data['mobile'];
            $info['email'] = $uinfo ? $uinfo['email'] : $data['email'];
            $info['last_ip'] = $data['last_ip'];
            $info['last_time'] = $data['last_time'];
            $this->session->set_userdata('userinfo', $info);
            
            $mess['reqStatus'] = true;
            $mess['url'] = site_url("account");
            echo JSON($mess);exit;
        }
    }
    //欢迎私信的发送
    private function send_dialog($userid,$room_name){
        $room_name = random_string('alnum', 6);
        $dialog_room = array(
            0=>array("room_name"=>$room_name,"dialog_from"=>13010,"dialog_to"=>$userid,"is_del"=>0,"is_show"=>0),
            1=>array("room_name"=>$room_name,"dialog_from"=>$userid,"dialog_to"=>13010,"is_del"=>0,"is_show"=>0)
        );
        $this->bbs_dialog_model->insert_dialog_room($dialog_room);
        $current_time = time();
        $data = array();
        $data['room_name'] = $room_name;
        $data['sender_from_id'] = 13010;
        $data['sender_to_id'] = $userid;
        $data['create_time'] = $current_time;
        $data['content'] = "Hello！ 我是弹溜溜小秘书 :) 欢迎您的到来，成为万千弹溜溜小伙伴中的一员。弹溜溜是个多元化的科技金融互动社群，在这里不仅可以参与最前沿的互联网金融体验，还可以发现更多志趣相投的伙伴、分享你的理财经验、交流投资心得等，更有可爱的客服妹纸随时为您排忧解难。对了，顺便问下，您是怎么知道弹溜溜的？";
        $data['is_read'] = 0;
        $data['is_show'] = 0;
        $this->bbs_dialog_model->insert_message($data);
    }
    
    //重新设置登录口令
    function set_login_key(){
        if($_POST){
            $check_code = md5(time()."TaN66");
            $this->session->set_userdata("login_code", $check_code);
            $mess['reqStatus'] = true;
            $mess['key'] = $check_code;
            echo JSON($mess);exit;
        }
    }
    
    //重新设置注册口令
    function set_reg_key(){
        if($_POST){
            $check_code = md5(time()."TaN66");
            $this->session->set_userdata("register_code", $check_code);
            $mess['reqStatus'] = true;
            $mess['key'] = $check_code;
            echo JSON($mess);exit;
        }
    }
}
